package com.weavernorth.create;

import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;


public class GetToken {
    private static Log log = LogFactory.getLog(GetToken.class.getName());
    public   String getToken() {

        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        RecordSet rsTwo = new RecordSet();
        RecordSet rsThree = new RecordSet();

        //获取当前时间戳
        long nowExpire=  System.currentTimeMillis();
        //全局变量：返回的token值
        String strToken="";
        //1.查询表中是否有无数据
        String sql = "select token , expire from uf_cct ";
        log.info("查询表中有无数据的sql:" + sql);
        rs.execute(sql);
        //2.如果表中有数据，取出时间戳做比较
        if (rs.next()) {
            String strExpire=Util.null2String(rs.getString("expire"));
            int intExpire = Integer.parseInt(strExpire);
            //3.当前时间戳大于表中时间戳时，重新获取数据
            if(nowExpire>intExpire){
                //表中数据无效，重新接口获取，返回值为String数组
                String[] resultArrayTwo =  invoking();
                //4.获取到数据后，修改表中数据
                if(!"".equals(resultArrayTwo[0])&& resultArrayTwo[0]!=null &&!"".equals(resultArrayTwo[1])&& resultArrayTwo[1]!=null){
                    //修改表中数据的sql
                    String sqlThree = "update uf_cct set  token ='" + resultArrayTwo[0] + "', expire = '" + resultArrayTwo[1]+"'";
                    bb.writeLog("修改的sql"+sqlThree);
                    rsThree.executeUpdate(sqlThree);
                    //数组中第一个值为token
                    strToken=resultArrayTwo[0];
                }
            }
            //5.表中数据有效，直接从表中获取
            else{
                strToken=rs.getString("token");
            }
        }
        //6.表中数据无值时，调用接口获取数据
        else {
            log.info("数据库没有token");
            String[] resultArray =  (invoking());
            //7.获取接口中值并新增数据
            if (!"".equals(resultArray[0])&& resultArray[0]!=null &&!"".equals(resultArray[1])&& resultArray[1]!=null){
                //新增数据的sql
                String  sqlTwo="insert into uf_cct (token,expire) values ('"+resultArray[0]+"','"+resultArray[1]+"')";
                bb.writeLog("增加的sql："+sqlTwo);
                rsTwo.executeUpdate(sqlTwo);
                //数组中第一个值为token
                strToken=resultArray[0];
            }
        }
        return strToken;
    }
    //8.获取接口值的方法
    public  String[] invoking() {
        log.info("调用接口获取token");
        BaseBean bb = new BaseBean();
        //全局变量：调用接口返回的状态值：0代表成功
        String strState="";
        //用于将接口的返回值格式化为JSONObject类型
        JSONObject joResult = new JSONObject();
        //建立数组来存储接口返回的token值和时间戳
        String arrayStr[] =new String[2];
        //传入的三个参数
        JSONObject json = new JSONObject();
        String code =Util.null2String(bb.getPropValue("porturl","code"));
        bb.writeLog("公司编码"+code);
        String userName =Util.null2String(bb.getPropValue("porturl","username"));
        bb.writeLog("用户名称"+userName);
        String passWord =Util.null2String(bb.getPropValue("porturl","password"));
        bb.writeLog("密码"+passWord);
        json.put("corpCode", code);
        json.put("userName", userName);
        json.put("password", passWord);
        //取出获取token的接口url
        String strUrl = Util.null2String(bb.getPropValue("porturl", "tokenurl"));
        //调用接口时传入的参数
        bb.writeLog("请求utl"+strUrl);
        bb.writeLog("请求体"+json);
        String strCode = "UTF-8";
        try {
            //调用接口的方法
            String resultStr = sendPost(strUrl, json, strCode,"");
           // bb.writeLog("返回值="+resultStr);
            //返回值转为JSONObject
            joResult = JSONObject.fromObject(resultStr);
          //  bb.writeLog("返回值转为jsonobject"+joResult);
            //返回值：代表成功与否的状态值
            strState = Util.null2String(joResult.get("state"));
        } catch (Exception e) {
            bb.writeLog("异常捕获="+e);
        }
        bb.writeLog("state的值" + strState);
        //如果状态值不为null并且为0时，将token和时间戳存储到数组中并返回
       if (!"".equals(strState)  && "0".equals(strState)) {
           //返回的数据
            String data = Util.null2String(joResult.get("data"));
            JSONObject jsonObject = JSONObject.fromObject(data);
            //返回的token和expire
            String strToken = Util.null2String(jsonObject.get("token"));
            String strExpire = Util.null2String(jsonObject.get("expire"));
            bb.writeLog("接口传回来token的值" + strToken);
            bb.writeLog("接口传回来expire的值" + strExpire);
            //将token和时间戳存放到数组中
            arrayStr[0]=strToken;
            arrayStr[1]=strExpire;
       }
        return  arrayStr;
    }



    public static String sendPost(String url, JSONObject jsonobject, String encoding,String token) {
        log.info("传入的token"+token);

        String body = "";
        try {
            //创建httpclient对象
            CloseableHttpClient client = HttpClients.createDefault();
            //创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);
            //装填参数
            StringEntity s = new StringEntity(jsonobject.toString(), "utf-8");
            //s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            //设置参数到请求对象中
            httpPost.setEntity(s);
//          System.out.println("请求地址："+url);

            //设置header信息
            //指定报文头【Content-type】、【User-Agent】
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            if (token != null && !"".equals(token)) {
                httpPost.setHeader("Authorization",  "Bearer " + token);
            }

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);

            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        }catch (Exception e){
            log.info(e+"请求异常");
        }

        return body;
    }



}